<template>
	<svg version="1.1" xmlns="http://www.w3.org/2000/svg" x="0" y="0" width="612" height="792" viewBox="0 0 612 792" :style="svgStyle">
		<path d="M107,0C48,0,0,48,0,107v578c0,59,48,107,107,107h398c59,0,107-48,107-107V186L426,0H107z" :fill="color" />
		<path :d="letterSvgPath" :transform="`translate(${textLeft}, ${textTop})`" fill="#FFFFFF" />
		<path d="M612,186L471,186c-30,0-45-30-45-45V0" opacity="0.3" fill="#FFFFFF" />
	</svg>
</template>

<script>
import opentypeJs from 'opentype.js';
export default {
	name: 'swFileIcon',
	props: {
		text: { type: String, default: 'pdf' },
		size: { type: String, default: '612' },
		color: { type: String, default: '#E3411F' }
	},
	data() {
		return {
			textTop: 0,
			textLeft: 0,
			letterSvgPath: ''
		};
	},
	computed: {
		svgStyle() {
			let size = Number(this.size);
			return {
				width: `${size}px`,
				height: `${(size * 792) / 612}px`
			};
		}
	},
	watch: {
		text: {
			handler(val) {
				this.formatSvgPath(val);
			},
			immediate: true
		}
	},
	methods: {
		formatSvgPath(val) {
			let text = val.toUpperCase();
			let fontSize = 612 / Math.max(2, text.length) + 40;
			let textPaths = this.$fontInstance.getPath(text, 0, 0, fontSize);
			let fontBounding = textPaths.getBoundingBox();
			let textHeight = fontBounding.y2 - fontBounding.y1;
			let textWidth = fontBounding.x2 - fontBounding.x1;
			this.letterSvgPath = textPaths.toPathData();
			this.textTop = (1188 + textHeight / 2) / 2;
			this.textLeft = (612 - textWidth) / 2;
		}
	}
};
</script>
